<template>
  <div class="http-client module-container">
    <div class="request-section">
      <div class="request-bar">
        <el-select v-model="request.method" class="method-select">
          <el-option value="GET">GET</el-option>
          <el-option value="POST">POST</el-option>
          <el-option value="PUT">PUT</el-option>
          <el-option value="DELETE">DELETE</el-option>
          <el-option value="PATCH">PATCH</el-option>
          <el-option value="HEAD">HEAD</el-option>
          <el-option value="OPTIONS">OPTIONS</el-option>
        </el-select>
        
        <el-input
          v-model="request.url"
          :placeholder="$t('http.url')"
          class="url-input"
          @keyup.enter="sendRequest"
        >
          <template slot="prepend" v-if="activeEnvironment">
            <el-tag size="mini">{{ activeEnvironment.name }}</el-tag>
          </template>
        </el-input>
        
        <el-button
          type="primary"
          @click="sendRequest"
          :loading="loading"
        >
          {{ $t('http.send') }}
        </el-button>
        
        <el-button @click="saveRequest" icon="el-icon-document">{{ $t('common.save') }}</el-button>
      </div>

      <el-tabs v-model="activeTab" class="request-tabs">
        <el-tab-pane :label="$t('http.params')" name="params">
          <ParamsEditor
            :params="request.params"
            @add="addParam"
            @update="updateParam"
            @remove="removeParam"
          />
        </el-tab-pane>
        
        <el-tab-pane :label="$t('http.headers')" name="headers">
          <HeadersEditor
            :headers="request.headers"
            @add="addHeader"
            @update="updateHeader"
            @remove="removeHeader"
          />
        </el-tab-pane>
        
        <el-tab-pane :label="$t('http.body')" name="body" v-if="hasBody">
          <BodyEditor
            :body="request.body"
            @update="updateBody"
          />
        </el-tab-pane>
        
        <el-tab-pane :label="$t('http.auth')" name="auth">
          <AuthEditor
            :auth="request.auth"
            @update="updateAuth"
          />
        </el-tab-pane>
        
        <el-tab-pane :label="$t('menu.settings')" name="settings">
          <RequestSettings
            :settings="request.settings"
            @update="updateSettings"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="response-section" v-if="response">
      <div class="response-header">
        <div class="response-status">
          <span v-if="response.error" class="status-code status-error">
            错误: {{ response.message || 'Network Error' }}
          </span>
          <span v-else class="status-code" :class="statusClass">
            {{ response.status }} {{ response.statusText }}
          </span>
          <span class="response-time" v-if="response.time">
            {{ response.time }}ms
          </span>
          <span class="response-size" v-if="response.size">
            {{ formatSize(response.size) }}
          </span>
        </div>
        
        <div class="response-actions">
          <el-button size="mini" @click="copyResponse">{{ $t('tools.jsonFormatter.copy') }}</el-button>
          <el-button size="mini" @click="downloadResponse">{{ $t('common.export') }}</el-button>
        </div>
      </div>

      <el-tabs v-model="responseTab" class="response-tabs" v-if="!response.error">
        <el-tab-pane :label="$t('http.client.responseBody')" name="body">
          <ResponseBody :data="response.data || ''" :contentType="responseContentType" />
        </el-tab-pane>
        
        <el-tab-pane label="响应头" name="headers">
          <ResponseHeaders :headers="response.headers || {}" />
        </el-tab-pane>
        
        <el-tab-pane label="Cookies" name="cookies">
          <ResponseCookies :cookies="response.cookies || []" />
        </el-tab-pane>
        
        <el-tab-pane label="测试" name="test">
          <TestResults :tests="response.tests || []" />
        </el-tab-pane>
      </el-tabs>
      
      <div v-else class="error-details">
        <el-alert
          :title="response.message || '请求失败'"
          type="error"
          :description="`错误代码: ${response.code || 'UNKNOWN'}`"
          show-icon>
        </el-alert>
      </div>
    </div>

    <div class="empty-response" v-else>
      <i class="el-icon-upload2"></i>
      <p>发送请求以查看响应</p>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import ParamsEditor from './components/ParamsEditor.vue'
import HeadersEditor from './components/HeadersEditor.vue'
import BodyEditor from './components/BodyEditor.vue'
import AuthEditor from './components/AuthEditor.vue'
import RequestSettings from './components/RequestSettings.vue'
import ResponseBody from './components/ResponseBody.vue'
import ResponseHeaders from './components/ResponseHeaders.vue'
import ResponseCookies from './components/ResponseCookies.vue'
import TestResults from './components/TestResults.vue'

export default {
  name: 'HttpClient',
  components: {
    ParamsEditor,
    HeadersEditor,
    BodyEditor,
    AuthEditor,
    RequestSettings,
    ResponseBody,
    ResponseHeaders,
    ResponseCookies,
    TestResults
  },
  data() {
    return {
      activeTab: 'params',
      responseTab: 'body'
    }
  },
  computed: {
    ...mapState('httpClient', ['currentRequest', 'response', 'loading']),
    ...mapState(['activeEnvironment']),
    
    request() {
      return this.currentRequest
    },
    
    hasBody() {
      return ['POST', 'PUT', 'PATCH', 'DELETE'].includes(this.request.method)
    },
    
    statusClass() {
      if (!this.response) return ''
      const code = this.response.status
      if (code >= 200 && code < 300) return 'status-success'
      if (code >= 300 && code < 400) return 'status-redirect'
      if (code >= 400 && code < 500) return 'status-client-error'
      if (code >= 500) return 'status-server-error'
      return ''
    },
    
    responseContentType() {
      if (!this.response || !this.response.headers) return ''
      return this.response.headers['content-type'] || ''
    }
  },
  methods: {
    ...mapActions('httpClient', [
      'sendRequest',
      'updateRequestField',
      'addHeader',
      'updateHeader',
      'removeHeader',
      'addParam',
      'updateParam',
      'removeParam'
    ]),
    
    updateBody(body) {
      this.updateRequestField({ field: 'body', value: body })
    },
    
    updateAuth(auth) {
      this.updateRequestField({ field: 'auth', value: auth })
    },
    
    updateSettings(settings) {
      this.updateRequestField({ field: 'settings', value: settings })
    },
    
    saveRequest() {
      this.$message.success('请求已保存')
    },
    
    copyResponse() {
      if (!this.response) return
      
      const text = typeof this.response.data === 'string' 
        ? this.response.data 
        : JSON.stringify(this.response.data, null, 2)
      
      navigator.clipboard.writeText(text).then(() => {
        this.$message.success('已复制到剪贴板')
      })
    },
    
    downloadResponse() {
      if (!this.response) return
      
      const text = typeof this.response.data === 'string' 
        ? this.response.data 
        : JSON.stringify(this.response.data, null, 2)
      
      const blob = new Blob([text], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `response_${Date.now()}.txt`
      a.click()
      URL.revokeObjectURL(url)
    },
    
    formatSize(bytes) {
      if (bytes < 1024) return bytes + ' B'
      if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
      return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
    }
  },
  watch: {
    'request.method'(newMethod) {
      if (!this.hasBody && this.activeTab === 'body') {
        this.activeTab = 'params'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.http-client {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
}

.request-section {
  flex: 0 0 auto;
  padding: $spacing-medium;
  background: #fff;
  border-bottom: 1px solid $border-color;
}

.request-bar {
  display: flex;
  gap: $spacing-base;
  margin-bottom: $spacing-medium;

  .method-select {
    width: 120px;
  }

  .url-input {
    flex: 1;
  }
}

.request-tabs {
  ::v-deep .el-tabs__header {
    margin: 0;
  }
}

.response-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background: #fff;
}

.response-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-base $spacing-medium;
  border-bottom: 1px solid $border-color;
  background: $border-extra-light;
}

.response-status {
  display: flex;
  align-items: center;
  gap: $spacing-medium;

  .status-code {
    font-weight: bold;
    
    &.status-success {
      color: $success-color;
    }
    
    &.status-redirect {
      color: $warning-color;
    }
    
    &.status-client-error {
      color: $danger-color;
    }
    
    &.status-server-error {
      color: $danger-color;
    }
    
    &.status-error {
      color: $danger-color;
    }
  }

  .response-time,
  .response-size {
    color: $text-secondary;
    font-size: $font-size-small;
  }
}

.response-tabs {
  flex: 1;
  display: flex;
  flex-direction: column;
  
  ::v-deep .el-tabs__content {
    flex: 1;
    overflow: auto;
    padding: $spacing-medium;
  }
}

.error-details {
  padding: $spacing-medium;
  flex: 1;
  overflow: auto;
}

.empty-response {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: $text-placeholder;
  
  i {
    font-size: 48px;
    margin-bottom: $spacing-medium;
  }
  
  p {
    font-size: $font-size-base;
  }
}

// Add padding to tab panes for proper spacing
.request-tabs,
.response-tabs {
  ::v-deep .el-tab-pane {
    padding: 20px;
  }
}
</style>